import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.util.Date;
import java.util.Enumeration;

public class ClientHandler extends Thread {
		
	private Server server;
	private Socket socket;
	private boolean loggedIn = false;
	String clientNick;
	Date now = new Date();
	
	public ClientHandler(Server server, Socket socket) {
		this.server = server;
		this.socket = socket;
		start();
	}
	
	public void run() {
		try {
			DataInputStream din = new DataInputStream(socket.getInputStream());
			while (true) {
				String in = din.readUTF();
				resolveRequest(in);
			}
		} catch(EOFException ie) {
		} catch(IOException ie) {
			ie.printStackTrace();
		} finally {
		}
			server.sendMessage("System", "***" + clientNick + " has left the room***");
			server.listModel.removeElement(clientNick);
			server.sendClientUpdate(clientNick, false);
			server.removeConnection(socket);
		}

	private void resolveRequest(String in) {
		String[] packet = in.split("\\|-\\|");
		if(packet[0].equals("Talk") && loggedIn){
			server.print(packet[1], packet[2]);
			server.sendMessage(packet[1], packet[2]);
		} else if(packet[0].equals("Register")){
			System.out.println("Registration Request");
			handleReg();
		} else if(packet[0].equals("Login")){
			System.out.println("Login Request");
			handleLogin(packet);
		}
	}

	private void handleReg() {
		// TODO Auto-generated method stub
		
	}

	private void handleLogin(String[] packet) {
		clientNick = packet[1];
		if(!loggedIn){
			server.sendMessage("System", "***" + clientNick + " has joined the room***");
			server.sendClientUpdate(clientNick, true);
			loggedIn = true;
			try {
				sendNewModel();
			} catch (IOException e) {
				e.printStackTrace();
			}
			server.listModel.addElement(clientNick);
		}
		else if(loggedIn){
			server.sendMessage("System", "***" + packet[2] + " has chaged his name to " + clientNick + "***");
			loggedIn = true;
			server.sendClientUpdate(packet[2], false);
			server.listModel.removeElement(packet[2]);
			server.sendClientUpdate(clientNick, true);
			server.listModel.addElement(clientNick);
		}
	}
	
	@SuppressWarnings("unchecked")
	public void sendNewModel() throws IOException {
		DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
		for (Enumeration e = server.listModel.elements(); e.hasMoreElements();) {
			String element = e.nextElement().toString();
			dout.writeUTF("clUpdate|-|" + element + "|-|true");
		}
	
	}
}